"use client";
// import { defaultEditorContent } from "@/lib/content";
import { novelcopy } from "@/lib/copyContent";
import { Button } from "@/components/ui/button"
// import { exportMarkdownToPdf } from '@/lib/markdownToPdf';
import {
  EditorCommand,
  EditorCommandEmpty,
  EditorCommandItem,
  EditorCommandList,
  EditorContent,
  type EditorInstance,
  EditorRoot,
  type JSONContent,
} from "novel";
import { ImageResizer, handleCommandNavigation,MarkdownExtension } from "novel/extensions";
import { useEffect, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import { defaultExtensions } from "./extensions";
import { ColorSelector } from "./selectors/color-selector";
import { LinkSelector } from "./selectors/link-selector";
import { NodeSelector } from "./selectors/node-selector";
import { MathSelector } from "./selectors/math-selector";
import { Separator } from "./ui/separator";

import { handleImageDrop, handleImagePaste } from "novel/plugins";
import GenerativeMenuSwitch from "./generative/generative-menu-switch";
import { uploadFn } from "./image-upload";
import { TextButtons } from "./selectors/text-buttons";
import { slashCommand, suggestionItems } from "./slash-command";
import { VmsCopy } from "@/types/Model";
import { useRouter } from 'next/navigation'
import { AudioSelector } from "./selectors/audio-selector";


const hljs = require('highlight.js');
const markdownExtension = MarkdownExtension.configure({
  // 配置选项
  html: true, // 是否允许 HTML
  linkify: true, // 自动将 URL 转换为链接
  breaks: true, // 将换行符转换为 <br>
});
const extensions = [...defaultExtensions, slashCommand,markdownExtension];

interface TailwindAdvancedEditorProps {
  copy?: VmsCopy; // You might want to specify a more specific type here
  saveCopy?: (copy: VmsCopy) => Promise<void>;
}

const TailwindAdvancedEditor = ({ copy, saveCopy }: TailwindAdvancedEditorProps) => {
  const [initialContent, setInitialContent] = useState<null | JSONContent>(null);
  const [saveStatus, setSaveStatus] = useState("unSaved");
  const [charsCount, setCharsCount] = useState<number>(0);
  const router = useRouter();

  const [openNode, setOpenNode] = useState(false);
  const [openColor, setOpenColor] = useState(false);
  const [openLink, setOpenLink] = useState(false);
  const [openAI, setOpenAI] = useState(false);
  const [openAudio,setOpenAudio] = useState(false);

  //Apply Codeblock Highlighting on the HTML from editor.getHTML()
  const highlightCodeblocks = (content: string) => {
    const doc = new DOMParser().parseFromString(content, 'text/html');
    doc.querySelectorAll('pre code').forEach((el) => {
      // @ts-ignore
      // https://highlightjs.readthedocs.io/en/latest/api.html?highlight=highlightElement#highlightelement
      hljs.highlightElement(el);
    });
    return new XMLSerializer().serializeToString(doc);
  };




  const debouncedUpdates = useDebouncedCallback(async (editor: EditorInstance) => {
    const json = editor.getJSON();
    const textContent = editor.getText(); // 获取纯文本内容
    const chineseCharCount = (textContent.match(/[\u4e00-\u9fa5]/g) || []).length; // 统计中文字符
    const wordCount = textContent.split(/\s+/).filter(Boolean).length; // 统计英文单词
    const totalCount = chineseCharCount + wordCount; // 综合统计
    
    setCharsCount(totalCount);
    window.localStorage.setItem("html-content", highlightCodeblocks(editor.getHTML()));
    window.localStorage.setItem("novel-content", JSON.stringify(json));
    window.localStorage.setItem("markdown", editor.storage.markdown.getMarkdown());
    setSaveStatus("unSaved");
  }, 500);

  // useEffect(() => {
  //   const content = window.localStorage.getItem("novel-content");
  //   if (content) setInitialContent(JSON.parse(content));
  //   else setInitialContent(defaultEditorContent);
  // }, []);

  useEffect(() => {
    if (copy?.content) {
      try {
        const parsedContent = JSON.parse(copy.content);
        setInitialContent(parsedContent);
      } catch (error) {
        console.error('Failed to parse copy content:', error);
        setInitialContent(null);
      }
    } else {
      setInitialContent(novelcopy(copy?.title, copy?.intro));
    }
  }, [copy]);

  const saveNovelCopy = async () => {
    try {
      if (!copy || !saveCopy) return;
      
      setSaveStatus('保存中...');
      const content = window.localStorage.getItem('novel-content');
      // const htmlContent = window.localStorage.getItem('html-content');
      const markdownContent = window.localStorage.getItem('markdown');

      // Extract title and intro from content if it exists
      if (content) {
        try {
          const parsedContent = JSON.parse(content);
          if (parsedContent?.content?.length > 0) {
            const heading = parsedContent.content.find((item: any) => item.type === 'heading');
            const paragraph = parsedContent.content.find((item: any) => item.type === 'paragraph');
            
            // if (heading?.content?.[0]?.text) {
            //   copy.title = heading.content[0].text;
            // }
            // if (paragraph?.content?.[0]?.text) {
            //   copy.intro = paragraph.content[0].text;
            // }
          }
        } catch (error) {
          console.error('Error parsing content:', error);
        }
      }
      const updatedCopy:VmsCopy = {
        ...copy,
        content: content || '', // Ensure content is always a string
        rich_content: markdownContent || '',
      };

      await saveCopy(updatedCopy);
      setSaveStatus('已保存');
    } catch (error) {
      console.error('保存失败:', error);
      setSaveStatus('保存失败');
    }
  };

  const handleExport = () => {
    if (!copy?.rich_content) return;
    
    try {
      const blob = new Blob([new TextEncoder().encode(copy.rich_content)], { 
        type: 'text/markdown;charset=utf-8' 
      });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${copy.title || 'untitled'}.md`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('Export error:', error);
    }
  };


  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // 检查是否是 Ctrl/Cmd + S
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();  // 阻止浏览器默认保存行为
        saveNovelCopy();     // 调用保存函数
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [saveNovelCopy]);  // 依赖 saveNovelCopy 以确保最新引用

  if (!initialContent) return null;

  return (
    <div className="relative w-full max-w-screen-xl">
      <div className="flex absolute left-5 top-5 z-10 mb-5 gap-2">
        <div className="rounded-lg bg-accent px-2 py-1 text-sm ">{saveStatus}</div>
        <div className={charsCount ? "rounded-lg bg-accent px-2 py-1 text-sm text-muted-foreground" : "hidden"}>
          {charsCount} Words
        </div>
      </div>
      <div className="flex absolute right-5 top-5 z-10 mb-5 gap-2">
        <Button 
          variant="outline" 
          size="sm"
          className="rounded-lg bg-accent px-2 py-1 text-sm text-muted-foreground hover:bg-accent/80 border-2 border-yellow-400 hover:border-yellow-500"
          onClick={() => window.open(`/scripts/${copy?.id}`,'_blank')}
        >
          <span className="font-bold text-yellow-500">脚本制作</span>
        </Button>
        <Button 
          variant="outline" 
          size="sm"
          className="rounded-lg bg-accent px-2 py-1 text-sm text-muted-foreground hover:bg-accent/80 border-2 border-blue-400 hover:border-blue-500"
          onClick={() => window.open(`/pptedit/${copy?.id}`,'_blank')}
        >
          <span className="font-bold text-blue-500">PPT制作</span>
        </Button>
        <Button 
          variant="outline" 
          size="sm"
          onClick={saveNovelCopy}
          className="rounded-lg bg-accent px-2 py-1 text-sm  hover:bg-accent/80"
        >
          保存
        </Button>
        
        <Button 
          variant="outline" 
          size="sm"
          onClick={handleExport}
          className="rounded-lg bg-accent px-2 py-1 text-sm text-muted-foreground hover:bg-accent/80"
        >
          导出
        </Button>
      </div>
      <EditorRoot>
        <EditorContent
          initialContent={initialContent}
          extensions={extensions}
          className="relative  p-24 min-h-[500px] w-full max-w-screen-xl border-muted bg-background sm:mb-[calc(20vh)] sm:rounded-lg sm:border sm:shadow-lg"
          editorProps={{
            handleDOMEvents: {
              keydown: (_view, event) => handleCommandNavigation(event),
            },
            handlePaste: (view, event) => handleImagePaste(view, event, uploadFn),
            handleDrop: (view, event, _slice, moved) => handleImageDrop(view, event, moved, uploadFn),
            attributes: {
              class:
                "prose prose-lg dark:prose-invert prose-headings:font-title font-default focus:outline-none max-w-full",
            },
          }}
          onUpdate={({ editor }) => {
            debouncedUpdates(editor);
            // setSaveStatus("Unsaved");
          }}
          slotAfter={<ImageResizer />}
        >
          <EditorCommand className="z-50 h-auto max-h-[330px] overflow-y-auto rounded-md border border-muted bg-background px-1 py-2 shadow-md transition-all">
            <EditorCommandEmpty className="px-2 text-muted-foreground">No results</EditorCommandEmpty>
            <EditorCommandList>
              {suggestionItems.map((item) => (
                <EditorCommandItem
                  value={item.title}
                  onCommand={(val) => item.command?.(val)}
                  className="flex w-full items-center space-x-2 rounded-md px-2 py-1 text-left text-sm hover:bg-accent aria-selected:bg-accent"
                  key={item.title}
                >
                  <div className="flex h-10 w-10 items-center justify-center rounded-md border border-muted bg-background">
                    {item.icon}
                  </div>
                  <div>
                    <p className="font-medium">{item.title}</p>
                    <p className="text-xs text-muted-foreground">{item.description}</p>
                  </div>
                </EditorCommandItem>
              ))}
            </EditorCommandList>
          </EditorCommand>

          <GenerativeMenuSwitch open={openAI} onOpenChange={setOpenAI}>
            <Separator orientation="vertical" />
            <NodeSelector open={openNode} onOpenChange={setOpenNode} />
            <Separator orientation="vertical" />

            <LinkSelector open={openLink} onOpenChange={setOpenLink} />
            <Separator orientation="vertical" />
            <MathSelector />
            <Separator orientation="vertical" />
            <TextButtons />
            <Separator orientation="vertical" />
            <ColorSelector open={openColor} onOpenChange={setOpenColor} />
            <Separator orientation="vertical" />
            <AudioSelector open={openAudio} onOpenChange={setOpenAudio} />
          </GenerativeMenuSwitch>
        </EditorContent>
      </EditorRoot>
    </div>
  );
};

export default TailwindAdvancedEditor;
